<template>
  <!--  查询 -->
  <div>
    <el-input placeholder="请输入客户ID" style="width:200px" v-model="queryId"></el-input>
    <el-button @click="queryById" type="success" plain>查询</el-button>
    <el-button @click="showCustomerDialog" type="primary" style="width: 100px; margin-left: 50px;font-weight: bolder; font-size: 16px">
      退住办理
    </el-button>
  </div>
  <!--  显示所有客户信息 table自动循环-->
  <div>{{errorMessage}}</div>
  <el-table :data="customerList">
    <el-table-column label="序号" type="index" width="60px"></el-table-column>
    <el-table-column prop="customerId" label="客户ID" width="80px"></el-table-column>
    <el-table-column prop="remarks" label="备注" width="80px"></el-table-column>
    <el-table-column prop="retreattime" label="退住时间" width="120px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="retreattype" label="退住类型" width="80px">
      <template #default="scope">
        {{scope.row.retreattype === 0? '正常退住' : (scope.row.retreattype === 1? '死亡退住' : (scope.row.retreattype === 2? '保留床位' : ''))}}
      </template>
    </el-table-column>
    <el-table-column prop="retreatreason" label="退住原因" width="120px"></el-table-column>
    <el-table-column prop="auditstatus" label="审批状态" width="80px">
      <template #default="scope">
        {{scope.row.auditstatus === 0? '已提交' : (scope.row.auditstatus === 1? '同意' : (scope.row.auditstatus === 2? '拒绝' : ''))}}
      </template>
    </el-table-column>
    <el-table-column prop="auditperson" label="审批人" width="80px"></el-table-column>
    <el-table-column prop="audittime" label="审批时间" width="120px" :formatter="formatDate"></el-table-column>
    <el-table-column  label="操作">
      <template #default="scope">
        <el-button type="primary" @click="showEditDialog(scope.row.id)">修改</el-button>
        <el-button type="danger" @click="removeOne(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="example-pagination-block">
    <el-pagination background
                   v-model:current-page="pageContains.pageNum"
                   v-model:page-size="pageContains.pageSize"
                   :page-sizes="[10,20,30,50,100]"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="pageContains.total"
                   @size-change="handleSizeChange"
                   @current-change="handlePageChange"
    />
  </div>

  <!--  客户信息对话框 -->
  <el-dialog v-model="customerDialog" :title="dialogTitle">
    <el-form :model="curCustomer">
      <!-- 客户选择 -->
      <el-form-item label="选择客户">
        <el-select v-model="newPreference.customer_id" placeholder="请选择客户" filterable clearable @change="onCustomerSelect" style="width: 200px;">
          <el-option v-for="customer in availableCustomerOptions" :key="customer.id" :label="customer.customerName" :value="customer.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="客户&emsp;ID">
        <el-col :span="11">
          <el-input v-model="curCustomer.customerId" disabled></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="备&emsp;&emsp;注">
        <el-col :span="11">
          <el-input v-model="curCustomer.remarks"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="退住时间">
        <el-col :span="11">
          <el-date-picker v-model="curCustomer.retreattime"></el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="退住类型">
        <el-col :span="11">
          <el-select v-model="curCustomer.retreattype">
            <el-option
                v-for="item in typeOptions"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="退住原因">
        <el-col :span="11">
          <el-input v-model="curCustomer.retreatreason"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="审批状态">
        <el-col :span="11">
          <el-select v-model="curCustomer.auditstatus">
            <el-option
                v-for="item in statusOptions"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>

      <el-form-item label="审批人：">
        <el-col :span="11">
          <el-input v-model="curCustomer.auditperson"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="审批时间">
        <el-col :span="11">
          <el-date-picker v-model="curCustomer.audittime"></el-date-picker>
        </el-col>
      </el-form-item>
    </el-form>
    <el-button @click="optOne()">{{buttonOpt}}</el-button>
  </el-dialog>
</template>

<script setup>
import {ref, onMounted, reactive} from "vue";
import http from '@/axios/http';
import qs from "qs";
import { ElMessage } from 'element-plus';
// 存放用户数据集合
let customerList = ref([]);

//报错提示
let errorMessage = ref("")

//模糊查询绑定的 客户ID
let queryId = ref("")

//对话框显示控制
let customerDialog = ref(false)

//客户信息，或者编辑已有客户的 绑定数据
let curCustomer = ref({});

//登记、修改客户信息弹出框的 标题和操作按钮  显示文字
let dialogTitle = reactive("")
let buttonOpt = reactive("")

//对话框操作类型：1：添加 2：编辑
let dialogOptType = reactive(1)
let size = 10; //当前显示多少行
let pageNum = 1; // 当前页码
let pageSize = 10; //每页显示行数

//当前页码信息
let pageContains = ref({})

//性别数组（其他字典值查询出来也是同样数据结构，使用方法类似）
let typeOptions = ref([
  {
    label: '正常退住',
    value: 0
  },{
    label: '死亡退住',
    value: 1
  },{
    label: '保留床位',
    value: 2
  }
])

let statusOptions = ref([
  {
    label: '已提交',
    value: 0
  },{
    label: '同意',
    value: 1
  },{
    label: '拒绝',
    value: 2
  }
])

const newPreference = reactive({
  customer_id: null,
  preferences: '',
  attention: '',
  remark: ''
});

const customerOptions = ref([]);
const availableCustomerOptions = ref([]);

// 获取客户列表（用于选择）
async function getCustomerOptions() {
  try {
    const res = await http.get('/lyy/get_Customer_List'); // 假设后端提供此接口
    if (res.data.result === 'success') {
      customerOptions.value = res.data.data.map(customer => ({
        id: customer.id,
        customerName: customer.customerName,
        customerId: customer.id // 假设数据库中客户 ID 字段名为 id
      }));
      availableCustomerOptions.value = [...customerOptions.value];
    } else {
      ElMessage.error('获取客户列表失败：' + res.data.error);
    }
  } catch (error) {
    console.error('请求后端接口失败：', error);
    ElMessage.error('请求后端接口失败，请稍后重试');
  }
}

onMounted(() => {
  getCustomerOptions();
});

// 当选择客户时触发
function onCustomerSelect(customerId) {
  const selectedCustomer = customerOptions.value.find(customer => customer.id === customerId);
  if (selectedCustomer) {
    curCustomer.value.customerId = selectedCustomer.customerId;
  }
}

//根据客户ID模糊查询客户信息
function queryById(){

  let param = {
    customerId: queryId.value
  }

  http.post('/lyy/get_backdown_by', param).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 customerList
        if(result.result === 'success'){
          customerList.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

//单击登录按钮事件
function showCustomerDialog(){
  dialogTitle = "退住信息登记";
  buttonOpt="录入"
  //弹出客户信息对话框
  customerDialog.value = true;
  dialogOptType = 1 //设置当前操作类型标志是 录入
  newPreference.customer_id = null;
  curCustomer.value.customerId = '';
}

//关闭客户信息对话框
function closeCustomerDialog(){
  customerDialog.value = false;
}

//页面初始化
onMounted(
    ()=>{
      init();
    }
)

function init(){
  //查询所有用户信息
  getAllCustomers();
  //查询需要的字典（{标志1: 值1, 标志2: 值2}）
  //用的时候取 字典[字段值（字典标志）]
}


function getAllCustomers(){
  let params = ref({
    size: size,
    pageNum: pageNum,
    pageSize: pageSize
  })

  http.post('/lyy/get_all_backdowns', params.value).then(
      (res) => {
        let result = res.data;
        // 返回结果传给 customerList
        if (result.result === 'success') {
          pageContains.value = result.data;
          //pageContains.list = null;
          customerList.value = result.data.list;

        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

//格式化日期
function formatDate(row, column) {
  let data = row[column.property];

  if (data == null) {
    return null;
  }

  let dt = new Date(data);
  return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
  //+ ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
}

function recordOne() {
  let param = curCustomer.value;
  http.post('/lyy/add_one_backdown', param).then(
      (res) => {
        let result = res.data;
        // 返回结果传给 customerList
        if (result.result ==='success') {
          // 从可用客户列表中移除已选择的客户
          const index = availableCustomerOptions.value.findIndex(customer => customer.id === newPreference.customer_id);
          if (index!== -1) {
            availableCustomerOptions.value.splice(index, 1);
          }
          // 调用更新客户状态的接口
          let customerId = curCustomer.value.customerId;
          http.post('/lyy/update_customer_state', {customerid: customerId, state: 2}).then(
              (updateRes) => {
                if (updateRes.data.result ==='success') {
                  //关闭对话框
                  closeCustomerDialog()
                  //刷新客户列表
                  getAllCustomers();
                } else {
                  ElMessage.error('更新客户状态失败：' + updateRes.data.error);
                }
              }
          );
        } else {
          errorMessage.value = result.error;
        }
      }
  )
}


//显示编辑对话框
function showEditDialog(id) {
  //根据id查询客户信息
  getBackdownInfo(id)

  //显示对话框
  console.log(id)
  customerDialog.value = true;
  dialogTitle = "退住信息修改";
  buttonOpt = "修改"

  dialogOptType = 2 //设置当前操作类型标志是 修改

}

function getBackdownInfo(id) {
  let param = {
    id: id
  }
  http.post('/lyy/getbackdownby_id', qs.stringify(param)).then(
      (res) => {
        let result = res.data;
        // 返回结果传给 customerList
        if (result.result === 'success') {
          curCustomer.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

//删除客户
function removeOne(id) {
  let param = {
    id: id
  }
  http.post('/lyy/removebackdown_by_id', qs.stringify(param)).then(
      (res) => {
        let result = res.data;
        // 返回结果传给 customerList
        if (result.result === 'success') {
          // 将删除的客户重新添加到可用客户列表中
          const deletedCustomer = customerOptions.value.find(customer => customer.id === curCustomer.value.customerId);
          if (deletedCustomer &&!availableCustomerOptions.value.some(customer => customer.id === deletedCustomer.id)) {
            availableCustomerOptions.value.push(deletedCustomer);
          }
          getAllCustomers();
        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

function editOne() {
  let param = curCustomer.value;
  http.post('/lyy/modifybackdownby_id', param).then(
      (res) => {
        let result = res.data;
        if (result.result === 'success') {
          //curCustomer.value = result.data;
          closeCustomerDialog();
          getAllCustomers();

        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

function optOne() {
  if (dialogOptType === 1) {
    recordOne()
  } else if (dialogOptType === 2) {
    editOne()
  }
}

//分页处理
const handlePageChange = (pageNum1) => {
  pageNum = pageNum1
  getAllCustomers()
}

const handleSizeChange = (pageSize1) => {
  pageSize = pageSize1
  getAllCustomers()
}
</script>

<style scoped>

</style>